//从京东联盟后台获取

const log = require('../../util/log')
const config = require('../../util/config')
const logger = require('log4js').getLogger();

async function getJdItems(obj) {
  try {
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client;
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    if (!obj.keyword) {
      return new Promise((resolve, reject) => {
        reject('缺少keyword')
      })
    }
    obj.keyword = obj.keyword.trim()
    if (obj.step !== 0) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd items')
      obj.step = 0
    }
    return new Promise((resolve, reject) => {
      this.loginJd().then(result => {
        step1.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, result => {
        reject(result)
      })
    })
  } catch (err) {
    log(err)
  }
}

async function step1(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client;
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll(".enterbtn").length'
    })
    if (result.value == 3) {
      // Page.navigate({
      //   url: 'https://media.jd.com/gotoadv/goods?pageSize=50'
      // })
      await Runtime.evaluate({
        expression: 'document.querySelectorAll(".enterbtn")[0].click()'
      })
      return step1_5.call(this, obj)
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step1.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step1_5(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client
    if (obj.step !== 1.5) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd items step 1.5')
      obj.step = 1.5
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'location.href'
    })
    if (result.value == 'https://media.jd.com/gotoadv/goods?pageSize=50') {
      return step2.call(this, obj)
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step1_5.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 2000)
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client
    if (obj.step !== 2) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd items step 2')
      obj.step = 2
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'location.href'
    })
    if (result.value != 'https://media.jd.com/gotoadv/goods?pageSize=50') {
      return step3.call(this, obj)
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("#keyword")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("#keyword")[0].value="' + obj.keyword + '"'
    })
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("#b_search")[0].click()'
    })
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    logger.error('[' + __filename + ':' + __line + ']', err)
  }
}

async function step3(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client
    if (obj.step != 3) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd items step 3', obj.keyword)
      obj.step = 3
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll(".product-list-b li")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      // if (Math.random() < 0.1) {
      //   return new Promise(resolve => {
      //     resolve([])
      //   })
      // }
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var items = []
    for (var i = 0; i < cnt; i++) {
      var item = {}
      var prefix = 'document.querySelectorAll(".product-list-b li")[' + i + '].'
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll("img")[0].src'
      })
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3.call(this, obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.img = result.value
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll(".tit")[0].innerText'
      })
      if (!result.value) {
        continue
      }
      item.title = result.value
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll(".img-wrap>a")[0].href'
      })
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3.call(this, obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.link = result.value
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll(".pri")[0].innerText'
      })
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3.call(this, obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.price = parseFloat(result.value.substring(1).replace(/,/i, ''))
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll(".rate>em")[0].innerText.trim()'
      })
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3.call(this, obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.rate = result.value.substring(0, result.value.length - 1)
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll(".shop")'
      })
      var _cnt = result.description.substring(9, result.description.length - 1)
      if (_cnt == 1) {
        item.shopName = '京东自营'
      }
      var {
        result
      } = await Runtime.evaluate({
        expression: prefix + 'querySelectorAll(".shop-name")'
      })
      var _cnt = result.description.substring(9, result.description.length - 1)
      if (_cnt == 1) {
        var {
          result
        } = await Runtime.evaluate({
          expression: prefix + 'querySelectorAll(".shop-name")[0].innerText'
        })
        item.shopName = result.value
      }
      items.push(item)
    }
    return new Promise(resolve => {
      resolve(items)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = getJdItems